// pages/xiangqing/xiangqing.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    packagepricelist: [],
    show: true, //控制下拉刷新的显示和隐藏
    distance: '',
    Appointmen: [],
    dataList: [],
    page: 1,
    headimg: '/images/banner01.png',
    id: '',
    details: [], //详情
    list: [{
        name: 21,
        flag: true
      }, {
        name: 22,
        flag: true
      }, {
        name: 23,
        flag: true
      },
      {
        name: 0,
        flag: true
      }, {
        name: 1,
        flag: true
      }, {
        name: 2,
        flag: true
      },
      {
        name: 3,
        flag: true
      }, {
        name: 4,
        flag: true
      }, {
        name: 5,
        flag: true
      },
      {
        name: 6,
        flag: true
      }, {
        name: 7,
        flag: true
      }, {
        name: 8,
        flag: true
      }, {
        name: 9,
        flag: true
      }, {
        name: 10,
        flag: true
      }, {
        name: 11,
        flag: true
      },
      {
        name: 12,
        flag: true
      }, {
        name: 13,
        flag: true
      }, {
        name: 14,
        flag: true
      }, {
        name: 15,
        flag: true
      }, {
        name: 16,
        flag: true
      }, {
        name: 17,
        flag: true
      },
      {
        name: 18,
        flag: true
      }, {
        name: 19,
        flag: true
      }, {
        name: 20,
        flag: true
      }
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    this.data.id = e.id
    this.data.distance = e.distance
    this.setData({
      distance: this.data.distance
    })
    console.log(e, 'e店铺已关闭')
    // this.getLocation(e);
    this.getStores()
    // 定时获取店铺列表
    // setInterval(()=>{
    //   this.getLocation(e);
    // },5000)
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    // this.setData({
    //     details:{},
    //     dataList:[],
    //     page:1,

    //   })

    wx.showLoading({
      title: '加载中...'
    });

    // 模拟异步请求最新数据
    setTimeout(() => {
      // 在这里执行获取最新数据的逻辑，比如调用接口获取数据
      this.setData({
        page: 1,
        show: false
      })
      this.getStores(); // 执行onReachBottom函数
      // 数据获取完成后隐藏加载提示
      wx.hideLoading();
      // 停止当前页面下拉刷新
      wx.stopPullDownRefresh();
      console.log('数据获取完成后隐藏加载提示')
    }, 500);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log('页面上拉触底事件的处理函数')
    this.setData({
      page: this.data.page + 1,

    })
    this.getStores()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  listhader: function () {
    const list = [{
        name: 21,
        flag: true
      },
      {
        name: 22,
        flag: true
      },
      {
        name: 23,
        flag: true
      },
      {
        name: 0,
        flag: true
      },
      {
        name: 1,
        flag: true
      },
      {
        name: 2,
        flag: true
      },
      {
        name: 3,
        flag: false
      },
      {
        name: 4,
        flag: false
      },
      {
        name: 5,
        flag: true
      },
      {
        name: 6,
        flag: true
      },
      {
        name: 7,
        flag: true
      },
      {
        name: 8,
        flag: true
      },
      {
        name: 9,
        flag: true
      },
      {
        name: 10,
        flag: true
      },
      {
        name: 11,
        flag: true
      },
      {
        name: 12,
        flag: true
      },
      {
        name: 13,
        flag: true
      },
      {
        name: 14,
        flag: true
      },
      {
        name: 15,
        flag: true
      },
      {
        name: 16,
        flag: true
      },
      {
        name: 17,
        flag: true
      },
      {
        name: 18,
        flag: true
      },
      {
        name: 19,
        flag: true
      },
      {
        name: 20,
        flag: true
      },
    ];

    const zd_time = ["1", "2", "3"];
    const zdTimeResult = Array.from({
      length: 24
    }, (_, i) => {
      const name = (i + 1).toString();
      const listObj = list.find((item) => item.name.toString() === name);
      const flag = listObj ? listObj.flag : false;
      return {
        name,
        flag
      };
    });

    zd_time.forEach((item) => {
      const index = parseInt(item) - 1;
      if (index >= 0 && index < 24) {
        zdTimeResult[index] = {
          name: item,
          flag: true
        };
      }
    });

    console.log(zdTimeResult);
  },

  getLocation: function (e) {
    var id = e.id;


    var stores = wx.getStorageSync('stores');
    //  var stores=this.data.dataList
    if (stores.length > 0) {
      var details = [];

      for (var i in stores) {
        if (id == stores[i].id) {
          const zd_time = stores[i].zd_time;
          const zdTimeResult = Array.from({
            length: 24
          }, (_, i) => {
            const name = (i + 1).toString();
            const listObj = this.data.list.find((item) => item.name.toString() === name);
            const flag = listObj ? listObj.flag : false;
            return {
              name,
              flag
            };
          });
          zd_time.forEach((item) => {
              const index = parseInt(item) - 1;
              if (index >= 0 && index < 24) {
                zdTimeResult[index] = {
                  name: item,
                  flag: false
                };
              }
            }

          );

          //   选中
          details.push({
            // zd_time:zdTimeResult,
            // id: stores[i].id,
            // address: stores[i].address,
            // city_id: stores[i].city_id,
            // close: stores[i].close,
            // content: stores[i].content,
            // distance: stores[i].distance,
            // image: stores[i].image,
            // label: stores[i].label,
            // label_ids: stores[i].label_ids,
            // lat: stores[i].lat,
            // lon: stores[i].lon,
            // min_price: stores[i].min_price,
            // mobile: stores[i].mobile,
            // name: stores[i].name,
            // open: stores[i].open,
            // rooms: stores[i].rooms,
          });

        }
      }

      this.setData({
        details: details
      })

    } else {
      // wx.removeStorageSync('stores');
      wx.showToast({
        title: '空空如也',
        icon: 'none'
      })
    }
  },
  callPhone: function (e) {
    var tel = e.target.dataset.tel;
    if (tel)
      wx.makePhoneCall({
        phoneNumber: tel,
        success: function () {},
      })
  },
  //   listenerBtnGetLocation:function(e){
  //     var lat = e.currentTarget.dataset.lat;
  //     var tel = e.currentTarget.dataset.lon;
  //     var name = e.currentTarget.dataset.name;
  //     var address = e.currentTarget.dataset.address;
  //     console.log(lat)
  //     console.log(tel)
  // // 上面
  // // wx.getLocation({
  // //     type: 'gcj02', // 坐标类型，默认为 wgs84
  // //     success: (res) => {
  // //       const latitude = res.latitude; // 用户当前的纬度
  // //       const longitude = res.longitude; // 用户当前的经度
  // //     },
  // //   });


  //     // 下面已经注释了
  //     wx.getLocation({
  //       //定位类型 wgs84, gcj02
  //       type: 'gcj02',
  //       success: function(res) {
  //         console.log(res)
  //         //return false
  //         wx.openLocation({
  //           //当前经纬度
  //           latitude: lat,
  //           longitude:tel,
  //           //缩放级别默认28
  //           scale: 28,
  //           //位置名
  //           name: name,
  //           //详细地址
  //           address: address,
  //           // //成功打印信息
  //           // success: function(res) {
  //           //   console.log(res)
  //           // },
  //           // //失败打印信息
  //           // fail: function(err) {
  //           //   console.log(err)
  //           // },
  //           // //完成打印信息
  //           // complete: function(info){
  //           //   console.log(info)
  //           // },
  //         })


  //       },
  //       fail: function(err) {
  //         console.log(err)
  //       },
  //       complete: function(info) {
  //         console.log(info)
  //       },
  //     })

  //   },
  listenerBtnGetLocation: function (e) {
    var lat = e.currentTarget.dataset.lat;
    var lon = e.currentTarget.dataset.lon;
    var name = e.currentTarget.dataset.name;
    var address = e.currentTarget.dataset.address;
    console.log(lat, lon, 'lonlon跳转了')

    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        wx.openLocation({
          latitude: Number(lat),
          longitude: Number(lon),
          scale: 28,
          name: name,
          address: address
        });
      },
      fail: function (err) {
        console.log(err);
      },
      complete: function (info) {
        console.log(info);
      }
    });
  },
  reserve: function (e) {
    var token = wx.getStorageSync('token')
    var userinfos = wx.getStorageSync('userinfo')
    if (!token || !userinfos) {
      wx.showToast({
        title: '用户未登录',
        icon: 'none',
        duration: 2000
      });
      // 获取用户图像
      wx.getUserProfile({
        desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: (res) => {
          console.log(res, '用户完善用户的资料')
          if (!res.userInfo) {
            wx.showToast({
              title: '未获取到用户信息',
              icon: 'none'
            });
            // return;
          }
          wx.setStorageSync('userinfo', res.userInfo);
        }
      })

      // 跳转到登录页面
      setTimeout(function () {
        wx.navigateTo({
          url: '/pages/login/login'
        });
      }, 1000); // 延迟1秒后跳转
      return false;
    }

    var id = e.target.dataset.id;
    var sataus = e.target.dataset.satatus;
    var list = e.currentTarget.dataset.list
    var getallprice = e.currentTarget.dataset.getallprice
    wx.setStorageSync('allrooms', list)
    wx.setStorageSync('getallprice', getallprice)
    // console.log(e.currentTarget.dataset.list,'e-------')
    // console.log()
    //  wx.setStorageSync('price_list', e.target.dataset.price_list)
    // 先判断状态是否等于4
    if (sataus == 4) {
      wx.showModal({
        title: '提示',
        content: '本包厢正在系统维护升级中，请您选择其它包厢，给您带来不便敬请谅解！',
        showCancel: false,
        confirmText: '知道了',
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
          }
        }
      })
      return false
    } else if (id)
      wx.navigateTo({
        url: '/pages/book/book?id=' + id + '&indexs=' + "quxiao",
      })
  },
  reservehader: function (e) {
    var id = e.target.dataset.id;
    if (id)
      wx.navigateTo({
        url: '/pages/book/book?id=' + id + '&indexs=' + "quxiao",
      })

  },
  getStores: function () {

    if (this.data.show == false) {
      // this.data.details.rooms=[]
      console.log(this.data.page, '-------------')
      this.setData({
        show: true,
        page: 1,
        dataList: [],
        details: {}
      })
      console.log(this.data.page, this.data.details, '-------------')
    }

    app.ajax({
      url: '/api/index/storeDetail',
      data: {
        id: this.data.id,
        page: this.data.page,
      },
      success: res => {
        if (res.code == 1) {
          let dataFromBackend = res.data.package;
          this.setData({
            packagepricelist: dataFromBackend
          });

          wx.setStorageSync('alldeposits', res.data.deposit)
          // if(this.data.page==1){}
          console.log(res.data.rooms, 'res.data.rooms--');
          if (res.data.rooms.length == 0) {
            // wx.showToast({
            //   title: '没有更多的了',
            //   icon: 'none'
            // });
            return false;
          }

          // 保存原来的数据
          let originalData = [...this.data.dataList];

          for (let room of res.data.rooms) {
            let existingRoom = originalData.find(item => item.id === room.id);

            if (existingRoom) {
              // 如果已经存在该房间，则更新其is_use字段
              const is_use = existingRoom.is_use.map(item => {
                const flag = room.is_use.includes(item.name);
                return {
                  ...item,
                  flag
                };
              });

              existingRoom.is_use = is_use;
            } else {
              // 如果是新房间，则直接添加到原来的数据中
              const is_use = [];
              for (let j = 1; j <= 24; j++) {
                const flag = room.is_use.includes(j);
                const name = j;
                const end = 4;
                is_use.push({
                  name,
                  flag,
                  end
                });
              }
              room.is_use = is_use;
              originalData.push(room);
            }
          }

          // 更新数据
          this.setData({
            dataList: originalData,
            details: {
              ...res.data,
              rooms: originalData
            }
          });

          console.log(this.data.details, '---');
        }
      },
      fail: res => {
        console.log(res + '请求错误', 'res失败了');
      }
    });

  },
  reserves(e) {
    let imageUrl = e.currentTarget.dataset.img
    console.log(e.currentTarget.dataset, 'eeee1')
    wx.previewImage({
      urls: [imageUrl], // 需要预览的图片链接列表
      current: imageUrl // 当前显示的图片链接
    });
  }



})